package com.yunduo.world.handler.encoder;

import com.google.protobuf.ByteString;
import com.yunduo.world.entity.EntityInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 自定义解码器，处理粘包问题
 */
public class DecodeUnPack extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        if (byteBuf == null) {
            return;
        }
        int dataLength = byteBuf.readableBytes();
        byte dataEnd = byteBuf.getByte(dataLength - 1);
        // 数据包末尾出现换行 切割数据包
        if ('\n' == dataEnd){
            byte[] dataPack = new byte[dataLength-1];
            byteBuf.readBytes(dataPack);
            ByteString parsePack = ByteString.copyFrom(dataPack);
            EntityInfo.Entity pack = EntityInfo.Entity.parseFrom(parsePack);
            out.add(pack);
            byteBuf.clear();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
